package com.newx.test.open.xyz2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Classname FileSender
 * @Description TODO
 * @Date 2025/1/9 9:59
 * @Created by yxl
 */
public class FileSender {
    private static final int COMMAND_TYPE_FILE = 0x01;
    private static final int BUFFER_SIZE = 1024;

    public static void sendFile(String filePath, Socket socket) throws IOException {
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead;

        while ((bytesRead = fis.read(buffer)) != -1) {
            // 构建协议帧
            ByteArrayOutputStream frame = new ByteArrayOutputStream();
            DataOutputStream frameOut = new DataOutputStream(frame);

            // 写入消息头
            frameOut.writeInt(bytesRead); // Length
            frameOut.writeShort(COMMAND_TYPE_FILE); // Command Type

            // 写入消息体
            frameOut.write(buffer, 0, bytesRead);

            // 写入校验和（可选）
            frameOut.writeShort(checksum(buffer, bytesRead));

            // 发送协议帧
            dos.write(frame.toByteArray());
            dos.flush();
        }

        fis.close();
        dos.close();
    }

    // 校验和计算函数（可选）
    private static short checksum(byte[] data, int length) {
        short sum = 0;
        for (int i = 0; i < length; i++) {
            sum += (short) (data[i] & 0xFF);
        }
        return sum;
    }

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("等待连接...");
        Socket clientSocket = serverSocket.accept();
        System.out.println("客户端已连接");

        sendFile("F:\\Desktop\\111.txt", clientSocket);
        clientSocket.close();
        serverSocket.close();
    }
}
